import { CONFIG, LeanCloudHeader, kimi_header } from "./config";

uni.addInterceptor("request", {
	invoke(options) {
		console.log(options);
		if (options.url.startsWith(CONFIG.leanCloud_url)) {
			const sessionToken = options.sessionToken;
			options.header = LeanCloudHeader(sessionToken);
		}
		if (options.url.startsWith(CONFIG.kimi_url)) {
			options.header = kimi_header;
		}
	}
});

const $request = (url, data = {}, method = 'GET', sessionToken = '') => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: data,
			method: method,
			header: {
				'Content-Type': 'application/json',
				...LeanCloudHeader(sessionToken)
			},
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};

uni.$request = $request;
uni.$get = (url, data = {}, sessionToken = '') => $request(url, data, 'GET', sessionToken);
uni.$post = (url, data = {}, sessionToken = '') => $request(url, data, 'POST', sessionToken);
uni.$put = (url, data, sessionToken = '') => $request(url, data, "PUT", sessionToken);
uni.$del = (url, data, sessionToken = '') => $request(url, data, "DELETE", sessionToken);

export default $request;
